package cn.itcast.health.admin.service;

import cn.itcast.health.commons.utils.RedisTemUtil;
import cn.itcast.health.interfaces.service.UserService;
import cn.itcast.health.pojo.Permission;
import cn.itcast.health.pojo.Role;
import cn.itcast.health.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("myDetailService")
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //创建list集合存储 用户名  密码 (List<GrantedAuthority>)权限
        List<Object> redisList = new ArrayList<>();

        //根据键用户名(唯一) 设置为rediskey取值
        List userMessageList = RedisTemUtil.getList(username);

        // redis取值判断是否为空,不是就取值返回
        if (userMessageList != null ){

            String userName = (String) userMessageList.get(0);
            String passWord = (String) userMessageList.get(1);
            List<GrantedAuthority> list = (List<GrantedAuthority>) userMessageList.get(2);
            return new org.springframework.security.core.userdetails.User(userName,passWord,list);

        }

        User user = userService.findUserByUserName(username);
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();

        for (Role role : roles) {
            //添加角色关键字
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //添加权限关键字
            for (Permission permission : role.getPermissions()) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //把GrantedAuthority参数添加到列表redisList 然后添加到redis里!
        redisList.add(user.getUsername());
        redisList.add(user.getPassword());
        redisList.add(list);
        //key为前端传的用户名(用户名唯一)
        RedisTemUtil.setList(username,redisList);
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);

    }

}
